﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/

using System.Threading;
using MbUnit.Framework;
using WatiN.Core;
using System;
using DotNetNuke.Tests.UI.WatiN.Utilities;
using DotNetNuke.Tests.UI.WatiN.Common;
using System.IO;
using DotNetNuke.Tests.UI.WatiN.Common.WatiNObjects;
using System.Text.RegularExpressions;

namespace DotNetNuke.Tests.UI.WatiN.BuildVerification
{
    [TestFixture]
    public class InstallTests : BVTBase
    {
        #region Public Members

        public string installVersion;

        #endregion

        #region Private Members

        private string installZipFileName;
        private string siteType;

        #endregion

        #region Protected Properties

        protected override string SiteType
        {
            get
            {
                return (BVTContext == null) ? String.Empty : BVTContext.Type;
            }
        }

       

        #endregion

        #region SetUp and TearDown

        [SetUp]
        public void SetUp()
        {
            //Make sure that the target folder is empty
            if (Directory.Exists(PhysicalPath))
            {
                Directory.Delete(PhysicalPath, true);
            }
            installZipFileName = String.Format("DotNetNuke_{0}_{1}_Install.zip", VersionType, TestVersion);

            //First Unzip Package to Website location
            ZipManager.ExtractZip(Path.Combine(TestEnvironment.PackagePath, installZipFileName), PhysicalPath);

            //Copy over the log4net config file
            string sourcePath = Path.Combine(TestFilesPath, "DotNetNuke.log4net.config");
            string destPath = Path.Combine(PhysicalPath, "DotNetNuke.log4net.config");
            File.Copy(sourcePath, destPath, true);


            //Next Setup Website 
            SetUpWebSite(PhysicalPath, TestUsers.DBUser.UserName, TestUsers.DBUser.Password);

            //Create Database
            DatabaseManager.CreateDatabase(TestContext, DatabaseName);

            //Add User
            DatabaseManager.AddUser(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password, new[] { "db_owner" });
            
            // Open a new Internet Explorer window and navigate to the website
            ieInstance = WatiNUtil.OpenIEInstance(SiteURL, SilentMode, IETimeOut, AutoCloseIE, AutoMovePointer);

            //Assert that we get the Install page
            //Assert.IsTrue(ieInstance.Span(Find.ById("wizInstall_lblStep0Title")).Exists);
        }

        [TearDown]
        public void TearDown()
        {
            //Make sure the user is logged off and clear the cache
            ieInstance.GoTo(SiteURL + "/LogOff.aspx");
            ieInstance.ClearCache();

            //Shut down Ie
            WatiNUtil.CloseIEInstance(ieInstance);

            //Recycle IIS App Pool
            IISManager.RecycleApplicationPool(ApplicationName);

            //Detach and copy database to holding location
            string destPath = DatabasePath + @"\" + SiteType;
            DatabaseManager.DetachAndCopyDatabase(DatabaseName, destPath, DatabaseName);

            //Remove Database Folder
            string testDatabaseDirectory = Path.GetFullPath(String.Format(@"{0}\{1}",
                                                        TestEnvironment.DatabasePath,
                                                        TestContext.Test.FullName));
            if (Directory.Exists(testDatabaseDirectory))
            {
                Directory.Delete(testDatabaseDirectory, true);
            }
                       
        }

        //[FixtureTearDown]
        //public void FixtureTearDown()
        //{
        //    //Generate a txt file of the test results and send this out 
        //    //string qaManagerEmail = "jogi@dnncorp.com";
        //    string qaAutomationDevEmail = "jennifer.nurse@dnncorp.com";


        //    //Create the text file
        //    File.WriteAllLines(CapturePath + "InstallTestResults.txt", testResults);

        //    System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
        //    message.From = "jmdnurse22@gmail.com";
        //    message.To = qaAutomationDevEmail;
        //    message.Subject = "Install Tests BVT results";
        //    message.Body = "This is a test";
        //    message.Attachments.Add(CapturePath + "InstallTestResults.txt");
        //    System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
        //    System.Web.Mail.SmtpMail.Send(message);

            
        //}

        #endregion

        #region Complete Installation Tests
        [Test]
        [CsvData(ResourcePath = "TestData.InstallList.csv", HasHeader=true)]
        public void Install_Should_Succeed(string version, string type)
        {
            installVersion = version;
            siteType = type;
            Assert.IsFalse(type.Equals("UpgradeOnly"), "UpgradeOnly cannot be used for running an install test. It is only used to indicate that the BVTs should not be run against installtion sites.");
            switch (type)
            {
                case "Auto":
                    Install_Should_Successfully_Complete_AutoInstall();
                    break;
                case "Typical":
                    Install_Should_Successfully_Complete_Typical_Install();
                    break;
                case "Custom":
                    Install_Should_Successfully_Complete_Custom_Install();
                    break;
                case "Qualifier":
                    Install_Should_Successfully_Complete_Typical_With_Object_Qualifier();
                    String logFilePath = Path.Combine(PhysicalPath, @"Providers\DataProviders\SqlDataProvider");
                    String[] logFiles = Directory.GetFiles(logFilePath, "??.??.??.log.resources");
                    //The regex string will pass if the file contains text, it will fail if the file is empty
                    String regexString = @"\S+";
                    Match match;
                    bool logsPass = true;
                    String logContents;
                    String failureFileName = "";
                    foreach (string logFile in logFiles)
                    {
                        //Check that the file is empty
                        logContents = File.ReadAllText(logFile);
                        match = Regex.Match(@logContents, regexString, RegexOptions.Singleline);
                        if(match.Success)
                        {
                            //The regex passed so something failed
                            failureFileName = logFile;
                            logsPass = false;
                        }
                    }
                    Assert.IsTrue(logsPass, "One of the log files contained text, indicating a failure with the install. Looking at " + failureFileName);
                    break;
                default:
                    break;
                    
            }

        }

        private void Install_Should_Successfully_Complete_Typical_With_Object_Qualifier()
        {
            //Arrange
            WizardPage wizardPage = new WizardPage(ieInstance, SiteURL, 0, DatabaseName);
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            if (!Directory.Exists(CapturePath + @"\Installs"))
            {
                Directory.CreateDirectory(CapturePath + @"\Installs");
            }

            //Act
            //Initial Install page - select install method
            wizardPage.SelectInstallMethod("Typical");
            wizardPage.Next.Click();

            //File Permissions Page
            wizardPage.PageNo = 1;
            CheckForYellowScreen("Checking File Permissions", "ObjectQualifier", @"The typical install was not started. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.Next.Click();

            //Configure Database Connection Page
            wizardPage.PageNo = 2;
            CheckForYellowScreen("Configure Database Connection", "ObjectQualifier", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SQLServerRadioButton.Click();
            if (wizardPage.DBIntegratedCheckbox.Checked)
            {
                wizardPage.DBIntegratedCheckbox.Checked = false;
                System.Threading.Thread.Sleep(2000);
            }
            wizardPage.ServerNameField.Value = TestEnvironment.DatabaseServer;
            wizardPage.DataBaseNameField.Value = DatabaseName;
            wizardPage.DataBaseUserNameField.Value = TestUsers.DBUser.UserName;
            wizardPage.DataBaseUserPasswordField.Value = TestUsers.DBUser.Password;
            wizardPage.ObjectQualifierTextField.Value = "Test";
            System.Threading.Thread.Sleep(2000);
            wizardPage.Next.Click();

            //Database Installation Scripts Page
            wizardPage.PageNo = 3;
            CheckForYellowScreen("Run Database Installation Scripts", "ObjectQualifier", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            //ieInstance.WaitUntilContainsText(new Regex(@"\w+ Installing Database Scripts", RegexOptions.IgnoreCase));
            while (!wizardPage.DatabaseInstallProgressDiv.Text.Contains("Completed Installing Database Scripts"))
            {
                System.Threading.Thread.Sleep(1000);
            }
            if (wizardPage.DatabaseInstallProgressDiv.Text.Contains("Failure") || wizardPage.DatabaseScriptResults.Text.Contains("Error") || wizardPage.DatabaseScriptResults.Text.Contains("Failure") || wizardPage.DatabaseScriptResults.Text.Contains("ERROR") || wizardPage.DatabaseScriptResults.Text.Contains("FAILURE"))
            {
                StreamWriter results = File.CreateText(CapturePath + @"\Installs\CustomDBResults.txt");
                results.Write(wizardPage.DatabaseScriptResults.Text);
                results.Close();
                Gallio.Framework.TestLog.WriteHighlighted("WARNING:");
                Gallio.Framework.TestLog.Write(@" An Error has occurred during the Database script installations however the tests may continue. For more information on the error view the screenshot for this test under Tests\Screen Shots.");
            }
            if (File.Exists(CapturePath + @"\Installs\ObjectQualifier.jpg"))
            {
                File.Delete(CapturePath + @"\Installs\ObjectQualifier.jpg");
            }
            ieInstance.CaptureWebPageToFile(CapturePath + @"\Installs\ObjectQualifier.jpg");
            Assert.IsFalse(wizardPage.DatabaseInstallProgressDiv.Text.Contains("Failure"));
            Assert.IsTrue(wizardPage.Next.Enabled);
            wizardPage.Next.Click();

            //Configure Host Account Page
            wizardPage.PageNo = 4;
            CheckForYellowScreen("Configure Host Account", "ObjectQualifier", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.HostUserNameField.Value = TestUsers.Host.UserName;
            wizardPage.HostPasswordField.Value = TestUsers.Host.Password;
            wizardPage.HostPasswordConfimationField.Value = TestUsers.Host.Password;
            wizardPage.HostEmailField.Value = TestUsers.Host.Email;
            wizardPage.Next.Click();

            //Configure Portal Page
            wizardPage.PageNo = 5;
            CheckForYellowScreen("Portal Title", "ObjectQualifier", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.AdminUserNameField.Value = TestUsers.Admin.UserName;
            wizardPage.AdminPasswordField.Value = TestUsers.Admin.Password;
            wizardPage.AdminPasswordConfimationField.Value = TestUsers.Admin.Password;
            wizardPage.AdminEmailField.Value = TestUsers.Admin.Email;
            wizardPage.Next.Click();

            //Installation
            //CheckForYellowScreen("Congratulations", "ObjectQualifier", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            
            // Temporary:
            //Execute a SQL Query that will disable pop ups
            //string disablePopUps = "INSERT INTO PortalSettings(PortalID, SettingName, SettingValue, CultureCode) VALUES (0, 'EnablePopups', 'False', 'en-us')";
            //try
            //{
            //    //Set the admin and host users update password value to false
            //    DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
            //                                                disablePopUps);
            //}
            //catch (Exception e)
            //{
            //    Gallio.Framework.TestLog.WriteLine(e);
            //}
            //END TEMP DB UPDATE
            //ieInstance.WaitUntilContainsText("Congratulations, you have successfully installed DotNetNuke.");
            //wizardPage.Finished.Click();

            //Assert
            Assert.IsTrue(ieInstance.Image(Find.ById("dnn_dnnLOGO_imgLogo")).Exists);
            Assert.IsTrue(homePage.LogoLink.Exists);
            Assert.IsTrue(homePage.LoginLink.Exists);
            Assert.IsTrue(homePage.RegisterLink.Exists);

            LoginPage loginPage = new LoginPage(homePage);
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
            HostSQLPage SQLPage = new HostSQLPage(homePage);
            SQLPage.SQLQueryTextField.Value = "SELECT LogTypeKey, LogProperties FROM dbo.Test_EventLog Where LogTypeKey LIKE '%EXCEPTION%'";
            SQLPage.ExecuteSQLLink.Click();
            System.Threading.Thread.Sleep(2000);
            if (!SQLPage.QueryResults.InnerHtml.Contains("The query did not return any data"))
            {
                TableRowCollection resultsRows = SQLPage.QueryResults.TableRows.Filter(Find.ByClass("Normal"));
                Gallio.Framework.TestLog.WriteHighlighted("WARNING: ");
                Gallio.Framework.TestLog.WriteLine("One or more exceptions occured during the install however the tests may continue. For more information view the test information from this test in the Screen Captures folder.");
                if (File.Exists(CapturePath + @"\Installs\" + siteType + "Exception.txt"))
                {
                    File.Delete(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                }
                StreamWriter sWriter = File.CreateText(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                foreach (TableRow row in resultsRows)
                {
                    sWriter.WriteLine(row.OwnTableCells[0].Text + ":");
                    sWriter.WriteLine(row.OwnTableCells[1].Text);
                }
                sWriter.Close();
            }

        }

        private void Install_Should_Successfully_Complete_Custom_Install()
        {
            //Arrange
            WizardPage wizardPage = new WizardPage(ieInstance, SiteURL, 0, DatabaseName);
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            if (!Directory.Exists(CapturePath + @"\Installs"))
            {
                Directory.CreateDirectory(CapturePath + @"\Installs");
            }

            //Act
            //Initial Install page - select install method
            wizardPage.SelectInstallMethod("Full");
            wizardPage.Next.Click();

            //File Permissions Page
            wizardPage.PageNo = 1;
            CheckForYellowScreen("Checking File Permissions", "Custom", @"The custom install was not started. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.Next.Click();

            //Configure Database Connection Page
            wizardPage.PageNo = 2;
            CheckForYellowScreen("Configure Database Connection", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SQLServerRadioButton.Click();
            System.Threading.Thread.Sleep(2000);
            if (wizardPage.DBIntegratedCheckbox.Checked == true)
            {
                wizardPage.DBIntegratedCheckbox.Checked = false;
                System.Threading.Thread.Sleep(2000);
            }
            wizardPage.ServerNameField.Value = TestEnvironment.DatabaseServer;
            wizardPage.DataBaseNameField.Value = DatabaseName;
            wizardPage.DataBaseUserNameField.Value = TestUsers.DBUser.UserName;
            wizardPage.DataBaseUserPasswordField.Value = TestUsers.DBUser.Password;
            wizardPage.Next.Click();

            //Database Installation Scripts Page
            wizardPage.PageNo = 3;
            CheckForYellowScreen("Run Database Installation Scripts", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            //ieInstance.WaitUntilContainsText(new Regex(@"\w+ Installing Database Scripts", RegexOptions.IgnoreCase));
            while (!wizardPage.DatabaseInstallProgressDiv.Text.Contains("Completed Installing Database Scripts"))
            {
                System.Threading.Thread.Sleep(1000);
            }
            if (wizardPage.DatabaseInstallProgressDiv.Text.Contains("Failure") || wizardPage.DatabaseScriptResults.Text.Contains("Error") || wizardPage.DatabaseScriptResults.Text.Contains("Failure") || wizardPage.DatabaseScriptResults.Text.Contains("ERROR") || wizardPage.DatabaseScriptResults.Text.Contains("FAILURE"))
            {
                StreamWriter results = File.CreateText(CapturePath + @"\Installs\CustomDBResults.txt");
                results.Write(wizardPage.DatabaseScriptResults.Text);
                results.Close();
                Gallio.Framework.TestLog.WriteHighlighted("WARNING:");
                Gallio.Framework.TestLog.WriteLine(@" An Error has occurred during the Database script installations however the tests may continue. For more information on the error view the screenshot for this test under Tests\Screen Shots.");
            }
            if (File.Exists(CapturePath + @"\Installs\Custom.jpg"))
            {
                File.Delete(CapturePath + @"\Installs\Custom.jpg");
            }
            ieInstance.CaptureWebPageToFile(CapturePath + @"\Installs\Custom.jpg");
            Assert.IsFalse(wizardPage.DatabaseInstallProgressDiv.Text.Contains("Failure"));
            Assert.IsTrue(wizardPage.Next.Enabled);
            wizardPage.Next.Click();

            //Configure Host Account Page
            wizardPage.PageNo = 4;
            CheckForYellowScreen("Configure Host Account", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.HostUserNameField.Value = TestUsers.Host.UserName;
            wizardPage.HostPasswordField.Value = TestUsers.Host.Password;
            wizardPage.HostPasswordConfimationField.Value = TestUsers.Host.Password;
            wizardPage.HostEmailField.Value = TestUsers.Host.Email;
            wizardPage.Next.Click();

            //Install Optional Modules Page 
            wizardPage.PageNo = 5;
            CheckForYellowScreen("Install Optional Modules", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SelectOptionalModule("Wiki (04.02.00)");
            wizardPage.SelectOptionalModule("Reports (05.01.00)");
            wizardPage.SelectOptionalModule("Events (05.00.02)");
            wizardPage.SelectOptionalModule("Announcements (04.00.03)");
            wizardPage.Next.Click();

            //Install Skins and Containers Page
            wizardPage.PageNo = 6;
            CheckForYellowScreen("Install Skins and Containers", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.Next.Click();

            //Install Language Packs Page
            wizardPage.PageNo = 7;
            CheckForYellowScreen("Install Language Packs", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SelectAllCheckBoxes();
            wizardPage.Next.Click();

            //Install Authenication Systems Page 
            wizardPage.PageNo = 8;
            CheckForYellowScreen("Install Authentication Systems", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SelectAllCheckBoxes();
            wizardPage.Next.Click();

            //Install Providers Page 
            wizardPage.PageNo = 9;
            CheckForYellowScreen("Install Providers", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SelectAllCheckBoxes();
            wizardPage.Next.Click();

            //Configure Portal Page
            wizardPage.PageNo = 10;
            CheckForYellowScreen("Portal Title", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.AdminUserNameField.Value = TestUsers.Admin.UserName;
            wizardPage.AdminPasswordField.Value = TestUsers.Admin.Password;
            wizardPage.AdminPasswordConfimationField.Value = TestUsers.Admin.Password;
            wizardPage.AdminEmailField.Value = TestUsers.Admin.Email;
            wizardPage.Next.Click();

            //Installation
          // CheckForYellowScreen("Congratulations", "Custom", @"An error occured during the custom install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            

            // Temporary:
            //Execute a SQL Query that will disable pop ups
            //string disablePopUps = "INSERT INTO PortalSettings(PortalID, SettingName, SettingValue, CultureCode) VALUES (0, 'EnablePopups', 'False', 'en-us')";
            //try
            //{
            //    //Set the admin and host users update password value to false
            //    DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
            //                                                disablePopUps);
            //}
            //catch (Exception e)
            //{
            //    Gallio.Framework.TestLog.WriteLine(e);
            //}
            //END TEMP DB UPDATE
            //ieInstance.WaitUntilContainsText("Congratulations, you have successfully installed DotNetNuke.");
            //wizardPage.Finished.Click();

            //Assert
            Assert.IsTrue(ieInstance.Image(Find.ById("dnn_dnnLOGO_imgLogo")).Exists);
            Assert.IsTrue(homePage.LogoLink.Exists);
            Assert.IsTrue(homePage.LoginLink.Exists);
            Assert.IsTrue(homePage.RegisterLink.Exists);

            LoginPage loginPage = new LoginPage(homePage);
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
            HostSQLPage SQLPage = new HostSQLPage(homePage);
            SQLPage.SQLQueryTextField.Value = "SELECT LogTypeKey, LogProperties FROM EventLog Where LogTypeKey LIKE '%EXCEPTION%'";
            SQLPage.ExecuteSQLLink.Click();
            System.Threading.Thread.Sleep(2000);
            if (!SQLPage.QueryResults.InnerHtml.Contains("The query did not return any data"))
            {
                TableRowCollection resultsRows = SQLPage.QueryResults.TableRows.Filter(Find.ByClass("Normal"));
                Gallio.Framework.TestLog.WriteHighlighted("WARNING: ");
                Gallio.Framework.TestLog.WriteLine("One or more exceptions occured during the install however the tests may continue. For more information view the test information from this test in the Screen Captures folder.");
                if (File.Exists(CapturePath + @"\Installs\" + siteType + "Exception.txt"))
                {
                    File.Delete(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                }
                StreamWriter sWriter = File.CreateText(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                foreach (TableRow row in resultsRows)
                {
                    sWriter.WriteLine(row.OwnTableCells[0].Text + ":");
                    sWriter.WriteLine(row.OwnTableCells[1].Text);
                }
                sWriter.Close();
            }

        }

        private void Install_Should_Successfully_Complete_Typical_Install()
        {
            //Arrange
            WizardPage wizardPage = new WizardPage(ieInstance, SiteURL, 0, DatabaseName);
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            if (!Directory.Exists(CapturePath + @"\Installs"))
            {
                Directory.CreateDirectory(CapturePath + @"\Installs");
            }

            //Act
            //Initial Install page - select install method
            wizardPage.SelectInstallMethod("Typical");
            wizardPage.Next.Click();

            //File Permissions Page
            wizardPage.PageNo = 1;
            CheckForYellowScreen("Checking File Permissions", "Typical", @"The typical install was not started. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.Next.Click();

            //Configure Database Connection Page
            wizardPage.PageNo = 2;
            CheckForYellowScreen("Configure Database Connection", "Typical", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.SQLServerRadioButton.Click();
            if (wizardPage.DBIntegratedCheckbox.Checked == true)
            {
                wizardPage.DBIntegratedCheckbox.Checked = false;
                System.Threading.Thread.Sleep(2000);
            }
            wizardPage.ServerNameField.Value = TestEnvironment.DatabaseServer;
            wizardPage.DataBaseNameField.Value = DatabaseName;
            wizardPage.DataBaseUserNameField.Value = TestUsers.DBUser.UserName;
            wizardPage.DataBaseUserPasswordField.Value = TestUsers.DBUser.Password;
            wizardPage.Next.Click();

            //Database Installation Scripts Page
            wizardPage.PageNo = 3;
            CheckForYellowScreen("Run Database Installation Scripts", "Typical", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            while(!wizardPage.DatabaseInstallProgressDiv.Text.Contains("Completed Installing Database Scripts"))
            {
                System.Threading.Thread.Sleep(1000);
            }
            if (wizardPage.DatabaseInstallProgressDiv.Text.Contains("Failure") || wizardPage.DatabaseScriptResults.Text.Contains("Error") || wizardPage.DatabaseScriptResults.Text.Contains("Failure") || wizardPage.DatabaseScriptResults.Text.Contains("ERROR") || wizardPage.DatabaseScriptResults.Text.Contains("FAILURE"))
            {
                StreamWriter results = File.CreateText(CapturePath + @"\Installs\CustomDBResults.txt");
                results.Write(wizardPage.DatabaseScriptResults.Text);
                results.Close();
                Gallio.Framework.TestLog.WriteHighlighted("WARNING:");
                Gallio.Framework.TestLog.WriteLine(@" An Error has occurred during the Database script installations however the tests may continue. For more information on the error view the screenshot for this test under Tests\Screen Shots.");
            }
            if (File.Exists(CapturePath + @"\Installs\Typical.jpg"))
            {
                File.Delete(CapturePath + @"\Installs\Typical.jpg");
            }
            ieInstance.CaptureWebPageToFile(CapturePath + @"\Installs\Typical.jpg");
            Assert.IsFalse(wizardPage.DatabaseInstallProgressDiv.Text.Contains("Failure"));
            Assert.IsTrue(wizardPage.Next.Enabled);
            wizardPage.Next.Click();

            //Configure Host Account Page
            wizardPage.PageNo = 4;
            CheckForYellowScreen("Configure Host Account", "Typical", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.HostUserNameField.Value = TestUsers.Host.UserName;
            wizardPage.HostPasswordField.Value = TestUsers.Host.Password;
            wizardPage.HostPasswordConfimationField.Value = TestUsers.Host.Password;
            wizardPage.HostEmailField.Value = TestUsers.Host.Email;
            wizardPage.Next.Click();

            //Configure Portal Page
            wizardPage.PageNo = 5;
            CheckForYellowScreen("Portal Title", "Typical", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            wizardPage.AdminUserNameField.Value = TestUsers.Admin.UserName;
            wizardPage.AdminPasswordField.Value = TestUsers.Admin.Password;
            wizardPage.AdminPasswordConfimationField.Value = TestUsers.Admin.Password;
            wizardPage.AdminEmailField.Value = TestUsers.Admin.Email;
            wizardPage.Next.Click();

            //Installation
            //CheckForYellowScreen("Congratulations", "Typical", @"An error occured during the typical install. For more details view the screenshot for this test under Tests\Screen Shots.", wizardPage);
            
            
            // Temporary:
            //Execute a SQL Query that will disable pop ups
            //string disablePopUps = "INSERT INTO PortalSettings(PortalID, SettingName, SettingValue, CultureCode) VALUES (0, 'EnablePopups', 'False', 'en-us')";
            //try
            //{
            //    //Set the admin and host users update password value to false
            //    DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
            //                                                disablePopUps);
            //}
            //catch (Exception e)
            //{
            //    Gallio.Framework.TestLog.WriteLine(e);
            //}
            //END TEMP DB UPDATE
           // ieInstance.WaitUntilContainsText("Congratulations, you have successfully installed DotNetNuke.");
           // wizardPage.Finished.Click();
                
            //Assert
            System.Threading.Thread.Sleep(1500);
            Assert.IsTrue(homePage.LogoImage.Alt.Equals("My Website"));
            Assert.IsTrue(homePage.LogoLink.Exists);
            Assert.IsTrue(homePage.LoginLink.Exists);
            Assert.IsTrue(homePage.RegisterLink.Exists);

            //LoginPage loginPage = new LoginPage(homePage);
            //loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            System.Threading.Thread.Sleep(2500);
            ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
            HostSQLPage SQLPage = new HostSQLPage(homePage);
            System.Threading.Thread.Sleep(1500);
            SQLPage.SQLQueryTextField.Value = "SELECT LogTypeKey, LogProperties FROM EventLog Where LogTypeKey LIKE '%EXCEPTION%'";
            SQLPage.ExecuteSQLLink.Click();
            System.Threading.Thread.Sleep(2000);
            if (!SQLPage.QueryResults.InnerHtml.Contains("The query did not return any data"))
            {
                TableRowCollection resultsRows = SQLPage.QueryResults.TableRows.Filter(Find.ByClass("Normal"));
                Gallio.Framework.TestLog.WriteHighlighted("WARNING: ");
                Gallio.Framework.TestLog.WriteLine("One or more exceptions occured during the install however the tests may continue. For more information view the test information from this test in the Screen Captures folder.");
                if (File.Exists(CapturePath + @"\Installs\" + siteType + "Exception.txt"))
                {
                    File.Delete(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                }
                StreamWriter sWriter = File.CreateText(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                foreach (TableRow row in resultsRows)
                {
                    sWriter.WriteLine(row.OwnTableCells[0].Text + ":");
                    sWriter.WriteLine(row.OwnTableCells[1].Text);
                }
                sWriter.Close();
            }
        }

        private void Install_Should_Successfully_Complete_AutoInstall()
        {
            //Arrange
            WizardPage wizardPage = new WizardPage(ieInstance, SiteURL, 0, DatabaseName);
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            if (!Directory.Exists(CapturePath + @"\Installs\"))
            {
                Directory.CreateDirectory(CapturePath + @"\Installs");
            }

            //Act
            //Initial Install page - select install method
            Thread.Sleep(100);
            wizardPage.SelectInstallMethod("Auto");
            wizardPage.Next.Click();

            //Wait until install completes
            if (!ieInstance.Text.Contains("Installing DotNetNuke"))
            {
                if (File.Exists(CapturePath + @"\Installs\AutoError.jpg"))
                {
                    File.Delete(CapturePath + @"\Installs\AutoError.jpg");
                }
                ieInstance.CaptureWebPageToFile(CapturePath + @"\Installs\AutoError.jpg");
            }
            Assert.IsTrue(ieInstance.Text.Contains("Installing DotNetNuke"));
            ieInstance.WaitUntilContainsText("Click Here To Access Your Portal");
            if (File.Exists(CapturePath + @"\Installs\Auto.jpg"))
            {
                File.Delete(CapturePath + @"\Installs\Auto.jpg");
            }
            ieInstance.CaptureWebPageToFile(CapturePath + @"\Installs\Auto.jpg");
            if (ieInstance.Text.Contains("Error") || ieInstance.Text.Contains("Failure"))
            {
                Gallio.Framework.TestLog.WriteHighlighted("WARNING:");
                Gallio.Framework.TestLog.WriteLine(@" An Error has occurred during the installation however the tests may continue. For more information on the error view the screenshot for this test under Tests\Screen Captures.");
            }

            // TEMPORARY:
            //Execute a SQL Query that will disable pop ups
            //string disablePopUps = "INSERT INTO PortalSettings(PortalID, SettingName, SettingValue, CultureCode) VALUES (0, 'EnablePopups', 'false', 'en-us')";
            //try
            //{
            //    //Set the admin and host users update password value to false
            //    DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
            //                                                disablePopUps);
            //}
            //catch (Exception e)
            //{
            //    Gallio.Framework.TestLog.WriteLine(e);
            //}
            //END TEMP DB UPDATE

            //Click on link to go to Home Page
            ieInstance.Link(Find.ByText("Click Here To Access Your Portal")).Click();

            //Assert
            Assert.IsTrue(homePage.LogoLink.Exists);
            Assert.IsTrue(homePage.LoginLink.Exists);
            Assert.IsTrue(homePage.RegisterLink.Exists);

            //Run some database updates
            string sqlUpdateString = @"UPDATE Users SET UpdatePassword='False'";
            string sqlAdminEmailUpdateString = @"UPDATE Users SET Email='" + TestUsers.Admin.Email + "' WHERE Username = 'admin'";
            string sqlHostEmailUpdateString = @"UPDATE Users SET Email='" + TestUsers.Host.Email + "' WHERE Username = 'host'";

            try
            {
                //Set the admin and host users update password value to false
                DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
                                                            sqlUpdateString);
                //Change the Admins EmailAddress to the EmailAddress listed for the admin in TestUsers
                DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
                                                            sqlAdminEmailUpdateString);
                //Change the Hosts EmailAddress to the EmailAddress listed for the host in TestUsers
                DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
                                                            sqlHostEmailUpdateString);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            LoginPage loginPage = new LoginPage(homePage);
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
            HostSQLPage SQLPage = new HostSQLPage(homePage);
            SQLPage.SQLQueryTextField.Value = "SELECT LogTypeKey, LogProperties FROM EventLog Where LogTypeKey LIKE '%EXCEPTION%'";
            SQLPage.ExecuteSQLLink.Click();
            System.Threading.Thread.Sleep(2000);
            if (!SQLPage.QueryResults.InnerHtml.Contains("The query did not return any data"))
            {
                TableRowCollection resultsRows = SQLPage.QueryResults.TableRows.Filter(Find.ByClass("Normal"));
                Gallio.Framework.TestLog.WriteHighlighted("WARNING: ");
                Gallio.Framework.TestLog.WriteLine("One or more exceptions occured during the install however the tests may continue. For more information view the test information from this test in the Screen Captures folder.");
                if (File.Exists(CapturePath + @"\Installs\" + siteType + "Exception.txt"))
                {
                       File.Delete(CapturePath + @"\Installs\" + siteType + "Exception.txt");
                }
               StreamWriter sWriter = File.CreateText(CapturePath + @"\Installs\" + siteType + "Exception.txt");
               foreach (TableRow row in resultsRows)
               {
                   sWriter.WriteLine(row.OwnTableCells[0].Text + ":");
                   sWriter.WriteLine(row.OwnTableCells[1].Text);
               }
               sWriter.Close();
            }           
        }

        #endregion

        #region Public Methods

        public void CheckForYellowScreen(string expectedPageTitle, string installType, string failMessage, WizardPage wizardPage)
        {
            bool noYellowScreen = wizardPage.PageTitle.Text.Contains(expectedPageTitle);
            if (!noYellowScreen)
            {
                if(File.Exists(CapturePath + @"\Installs\" + installType + "Error.jpg"))
                {
                    File.Delete(CapturePath + @"\Installs\" + installType + "Error.jpg");
                }
                ieInstance.CaptureWebPageToFile(CapturePath + @"\Installs\" + installType + "Error.jpg");
            }
            Assert.IsTrue(noYellowScreen, failMessage);
        }


        #endregion
    }
}
